package com.example.mydemo.log;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.stream.Collectors;


//  请求日志记录切面

//@Aspect
//@Component
public class LogRequestAspect111 {

    private static final Logger log = LoggerFactory.getLogger(LogRequestAspect111.class);

    @Autowired
    private RequestLogService requestLogService;



    /**
     * 定义切入点：所有带有@Loggable注解的方法
     */
    @Pointcut("@annotation(com.example.mydemo.log.LogRequest)")
    public void loggableMethods() {}

    @Before("loggableMethods()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("runBefore()执行前执行了！！！！！");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            log.error("无法获取 HttpServletRequest，当前线程可能不在 HTTP 请求上下文中");
            return joinPoint.proceed();
        }
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest();
        LocalDateTime now = LocalDateTime.now();
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        String params = Arrays.stream(args)
                .map(Object::toString)
                .collect(Collectors.joining(", "));


        // 构造日志对象
        RequestLog requestLog = new RequestLog();
        requestLog.setRequestId(IdWorker.getId());  // 生成唯一 ID
        requestLog.setRequestTime(now);
        requestLog.setSourceIp(request.getRemoteAddr());
        requestLog.setSourceSystem(request.getHeader("User-Agent"));
        requestLog.setRequestMethod(request.getMethod());
        requestLog.setRequestUrl(request.getRequestURI());
        requestLog.setRequestParams(params);
        requestLog.setCreateTime(now);

        // 保存日志
        requestLogService.save(requestLog);

        return joinPoint.proceed();
    }


//    /**
//     * 对Controller层的方法进行日志记录
//     */
//    @Pointcut("execution(* com.example.mydemo.controller..*(..))")
//    public void controllerLog() {}
//
//    @Before("controllerLog()")
//    public void doBefore(JoinPoint joinPoint) {
//        // 获取请求信息
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        if (attributes == null) {
//            return;
//        }
//
//        HttpServletRequest request = attributes.getRequest();
//
//        // 记录请求信息
//        log.info("==============================请求开始==============================");
//        log.info("请求URL: {}", request.getRequestURL().toString());
//        log.info("HTTP方法: {}", request.getMethod());
//        log.info("IP地址: {}", request.getRemoteAddr());
//        log.info("类方法: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
//        log.info("请求参数: {}", Arrays.toString(joinPoint.getArgs()));
//    }
//
//    @AfterReturning(returning = "result", pointcut = "controllerLog()")
//    public void doAfterReturning(Object result) {
//        log.info("返回结果: {}", result);
//        log.info("==============================请求结束==============================");
//    }

}
